<template>
	<view :class="pageClass" bounces='true'  enhanced='true' :style="pageStyle"  v-if="pageReady">
		<moxi-nav :set="navSet"></moxi-nav>
		<view style="background:#F5F5F5;background-attachment: scroll;position: relative;">
			<view scroll-y>
				<view style="padding: 12px 12px 0 12px;">
					<view class="orderconfirm-top">
						<view>
							<view style="display: flex;gap: 6px;justify-content: space-between;padding-bottom: 12px;">
								<view>
									<view
										style="display: flex;gap: 6px;padding-bottom: 6px; font-weight: bold;align-items: center;" @click="mapClick()">
										<text>{{merchantname}}</text>
										<u-icon name="arrow-right" size="10"></u-icon>
									</view>
									<view style="display: flex;gap: 6px;align-items: center;">
										<u-icon name="map" size="10"></u-icon>
										<text
											style="color: #999999;font-size: 12px;overflow: hidden;text-overflow: ellipsis;width: 190px;white-space: nowrap;">{{address}}</text>
									</view>
								</view>
								<view>
									<image src="https://file.moxikeji.net/images/2025/daohangtu.png"
										style="width: 30px;height: 30px;"></image>
								</view>
							</view>
							<view class="table-number" v-if="isZH">
								<view>
									<view>桌号</view>
								</view>
								<view>
									<view>{{tNum}}</view>
								</view>
							</view>
							<view style="display: flex;gap: 12px;padding-top: 12px;">
								<view style="width: 100%;height: 46px;">
									<!-- #ifndef MP-ALIPAY -->
									
									<u-button  :plain="!isDineIn"  :color="isDineIn ? colorList[4] : colorList[4]" 
										:custom-style="{height: '100%',width: '100%',borderRadius: '12px'}"
										@click="dineInClick()">堂食</u-button>
									<!-- #endif -->

									<!-- #ifdef MP-ALIPAY -->
									<button  :style="{
									        height: '46px',
									        width: '100%',
									        borderRadius: '12px',
									        border: isDineIn ? `1px solid ${colorList[4]}` : '1px solid #D8D8D8',
									        color: isDineIn ? colorList[4] : '#666',
											// backgroundColor: ,
									        fontSize: '16px',
									        lineHeight: '46px',
									        padding: 0
									      }" @tap="dineInClick">
										堂食
									</button>
									<!-- #endif -->

								</view>
								<view style="width: 100%;height: 46px;">
									<!-- #ifndef MP-ALIPAY -->
									<u-button  :plain="!isPack"  :color="!isPack ? colorList[4] : colorList[4]"
										:custom-style="{height: '100%',width: '100%',borderRadius: '12px',}"
										@click="packClick()">打包</u-button>
									<!-- #endif -->
									<!-- #ifdef MP-ALIPAY -->
									<button :style="{
									        height: '46px',
									        width: '100%',
									        borderRadius: '12px',
									        border: isPack ? `1px solid ${colorList[4]}` : '1px solid #D8D8D8',
									        color: isPack ? colorList[4] : '#666',
									        background: 'transparent',
									        fontSize: '16px',
									        lineHeight: '46px',
									        padding: 0
									      }" @tap="packClick">
										打包
									</button>
									<!-- #endif -->

								</view>
							</view>
						</view>
					</view>
				</view>

				<view style="padding: 12px 12px 0 12px;">
					<view class="orderconfirm-top">
						<view >
							<view style="display: flex;gap: 6px;justify-content: space-between;padding-bottom: 12px;">
								<view  style="display: flex;gap:12px;flex: 1;flex-direction: column;">
									<view v-for="(item,index) in this.parsedItems" style="display: flex;">
										<view style="width: 80px; height: 80px; margin-right: 8px;">
											<img
											:src="item.img"
											style="width: 80px;
			height: 80px;border-radius: 8px;"
										/>
										</view>
										
										<view class="set-meal">
											<view style="font-size: 14px;font-weight: bold;">{{item['name']}}</view>
											<view v-for="(v,k) in item.specs"
												style="font-size: 10px;color: #999999;font-size: 12px;">
												{{v.groupName}} ：{{v.name}}</view>
											<view
												style="display: flex;justify-content: space-between;align-items: center;">
												<view style="font-size: 14px;font-weight: bold;">￥{{item['totalPrice'].toFixed(2)}}</view>
												<view style="font-size: 12px;color: #999999;">x{{item['count']}}</view>
											</view>
										</view>
									</view>
	
								</view>
							</view>
							
							<view class="table-conut">
								<view>
									<text style="color: #999999;font-size: 14px;">合计：</text>
								</view>
								<view style="display: flex;align-items: baseline;">
									<view style="font-size: 12px;">￥</view>
									<view style="font-size: 18px;font-weight: bold;">{{totalprice}}</view>
								</view>
							</view>
							
						</view>
					</view>
				</view>
				<view style="padding: 12px 12px 0 12px;height: 250px; ">
					<view class="orderconfirm-top">
						<view >
							<view style="display: flex;flex-direction: column;padding-bottom: 12px;">
								<text style="font-size: 14px;color: #3D3D3D;">备注</text>
								<!-- #ifndef MP-ALIPAY || MP-BAIDU || MP-WEIXIN || MP-TOUTIAO -->
								<view style="height: 80px;">
									<u--textarea style="background-color: #F5F5F5;" v-model="value1" border="none"
										placeholder="可以在这里告诉我您喜欢的口味噢">{{parsedItems[0]['desc']}}</u--textarea>
								</view>
								<!-- #endif -->
								
								<!-- #ifdef MP-ALIPAY || MP-BAIDU || MP-WEIXIN || MP-TOUTIAO -->
								<view >
									<textarea
										:style="{<!-- #ifdef MP-BAIDU || MP-TOUTIAO -->'box-sizing':'border-box',<!-- #endif -->}"
										style="background: #F5F5F5;height: 80px;border-radius: 10px;padding: 8px;"
										name="value1" v-model="value1" placeholder-style="font-size: 14px;"
										placeholder="可以在这里告诉我您喜欢的口味噢"></textarea>
								</view>
								<!-- #endif -->
								
							</view>
						</view>
					</view>
					
				</view>
				
			</view>
			
			
		</view>
		
		<view
			style="background: #ffffff; display: flex;align-items: center;
			padding: 16px 0px;justify-content: space-between;bottom: 0px;position: fixed;width: 100%;">
			<view style="display: flex;width: 100%;padding: 0 12px;justify-content: space-between;align-items: center;">
				<view style="display: flex;align-items: baseline;color: #3D3D3D;">
					<view style="margin-right: 12px;">
						<view style="font-size: 16px;">
							共{{count}}件
						</view>
					</view>
					<view>
						<view style="display: flex;">
							<view style="font-size: 16px;">
								合计：
							</view>
							<view style="font-weight: bold;display: flex;align-items: center;"
								:style="{color:colorList[4]}">
								<view style="font-size: 12px;">￥</view>
								<view style="font-size: 18px;">{{totalprice}}</view>
							</view>
						</view>
					</view>
				</view>
				
				<view style="width: 128px;height: 40px;">
					<u-button :custom-style="{height: '100%', width: '100%',borderRadius: '20px'}" :color="colorList[4]"
						@click="submitOrder">提交订单</u-button>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
import { onLoad } from '../uni_modules/uview-ui/libs/mixin/mixin';

	export default {
		data() {
			return {
				isZH: false,
				//备注内容
				value1: '',
				isDineIn: true,
				isPack: false,
				parsedItems: [],
				//规格单独处理
				specs:[],
				address:[],
				merchantname:'',
				merchant:{
					'la':0,
					'ln':0
				},
				//计算总价格
				totalprice:0,
				//计算下单商品的数量
				count:0,
				packback:0,
				mid:0,
				tid:0,
				tNum:''
				
			}
		},

		methods: {
			//桌号信息
			getTable(mid,tid){
				console.log('tid:',tid);
				console.log('mid:',mid);
				if(tid == undefined || tid == 0){
					return;
				}else{
					this.isZH = true;
					this.moxiPost('/plugin/order/user/user/gettable',{'mid':mid,'tid':tid},(res)=>{
							this.tNum = res.data.name
					})
				}
				
			},
			//获取店名和店家位置
			getmerchantinfo(mid){
				this.moxiPost(
				"/plugin/order/index/merchant/getaddress",
				{'mid':mid},
				(res)=>{
					console.log(res.data);
					this.merchantname = res.data.name;
					this.merchant.la = res.data.la;
					this.merchant.ln = res.data.ln;
					this.address = res.data.address;
					}
				)
			},
			dineInClick() {
				this.isPack = false;
				this.isDineIn = true;
				this.packback = 0;
			},
			packClick() {
				this.isPack = true;
				this.isDineIn = false;
				this.packback = 1;
			},
			//地图导航
			mapClick() {
				
				if (!this.merchant.ln || !this.merchant.la) {
					uni.showToast({
						title: '暂无位置信息',
						icon: 'none'
					});
					return;
				}
					// console.log(this.merchant);
					// return false;
				const latitude = Number(this.merchant.la);
				const longitude = Number(this.merchant.ln);
				const name = this.address || '目的地';
				// #ifdef MP-ALIPAY
				my.openLocation({
					latitude,
					longitude,
					name,
					address: this.address || '',
					success: () => console.log('支付宝地图打开成功'),
					fail: (err) => console.error('支付宝地图打开失败', err),
				});
				// #endif
			
				// #ifndef MP-ALIPAY
				uni.openLocation({
					latitude,
					longitude,
					name,
					success: () => console.log('地图打开成功'),
					fail: (err) => console.error('地图打开失败', err),
				});
				// #endif
			},
			//提交订单   -- 支付调用（支付时间设置10分钟）  -- 完成跳转详情 （取餐号，餐桌号，菜品）  
			submitOrder() {
				//处理商品数据
				const parseitemstr = encodeURIComponent(JSON.stringify(this.parsedItems));
				this.moxiPost(
				'/plugin/order/user/user/createdorder',
				{
					'mid':this.mid,
					'goods':this.parsedItems,
					'tid':this.tid,
					'desc':this.value1,
					'packback':this.packback
				},
				(res)=>{
					console.log('提交订单信息:',res);
					const payId = res.pay_id;
					if(res.error){
						//清空购物。返回上一页 清空传来的数据
						this.msg(res.error)
						//返回上一页 再清空购物车？
						uni.navigateBack(-1);
						this.parsedItems = [];
						return;
					}
					//跳转要加上pay_id\订单id
					// console.log("/pages/index/pay?pay_id="+payId+"&btn_name=查看订单&path="+encodeURIComponent("/plugin_order/orderinfo?order_id="+res.data.order_id+'&mid='+this.mid + '&tNum=' + this.tNum));
					this.navto("/pages/index/pay?pay_id="+payId+"&btn_name=查看订单&path="+encodeURIComponent("/plugin_order/orderinfo?order_id="+res.data.order_id+'&mid='+this.mid + '&tNum=' + this.tNum))
					
				});
				
								return false
			
			},
			
			
		},
		mounted() {
			// this.parseItems();
			
		},
		onLoad(option) {
			console.log('option:',option);
			this.mid = option.mid
			if(option.tid !== 0){
				this.tid = option.tid
				this.getTable(option.mid,option.tid)
			}
			//做个缓存
			uni.setStorageSync('selected',option.mid);
			const selectedGoods = uni.getStorageSync('plugin_order_selectedGoods');
			//接收参数加上解码
			var item = JSON.parse(selectedGoods);
				this.parsedItems = item;
				//计算总价格
				this.parsedItems.forEach((item,index)=>{
					if(item['totalPrice']){
						//处理精度   转成浮点数，再保留2位
						this.totalprice = (parseFloat(this.totalprice) + parseFloat(item['totalPrice'])).toFixed(2);
					}
					if(item['count']){
						this.count += item['count']
					}
				});
				this.parsedItems.forEach((item) => {
				    if (item.specs && Array.isArray(item.specs)) {
				        // 将每个 item 的 specs 合并到 this.specs 数组中
				        this.specs = this.specs.concat(item.specs);
				    }
				});
			//获取商家信息
			console.log('传过来的信息:',this.parsedItems);
			this.getmerchantinfo(this.mid)
		}
	}
</script>

<style lang="scss" scoped>
	/* #ifdef MP-ALIPAY */
	button::after {
		border: none !important;
	}

	button {
		box-sizing: border-box;
	}

	/* #endif */
	.orderconfirm-top {
		background: #FFFFFF;
		border-radius: 12px;
		box-sizing: border-box;
		padding: 12px;
	}

	.table-number {
		display: flex;
		justify-content: space-between;
		font-size: 14px;
		color: #3D3D3D;
		border-top: 1px solid #F6F6F6;
		border-bottom: 1px solid #F6F6F6;
		padding: 12px 0;
	}

	.dine-in-pack {
		border-radius: 12px;
	}

	.table-conut {
		display: flex;
		justify-content: space-between;
		font-size: 14px;
		color: #3D3D3D;
		border-top: 1px solid #F6F6F6;
		padding: 12px 0;
		align-items: center;
	}

	.set-meal {
		display: flex;
		flex: 1;
		flex-direction: column;
		justify-content: space-around;
		margin-left: 10px;
	}
</style>